import { Avatar, message, Modal, Popconfirm, Upload } from 'antd'
import { useEffect, useState } from 'react';
import { NavLink } from 'react-router-dom'
import { LoadingOutlined, PlusOutlined, UserOutlined, EditOutlined } from '@ant-design/icons';
import Text from 'antd/lib/typography/Paragraph';
import style from './style.module.less'
import { RcFile, UploadChangeParam, UploadFile } from 'antd/lib/upload/interface';
import { getUserInfo, logout, updateUserInfo } from '../../services/api';
import MyArticle from '../../components/MyArticle';
import moment from 'moment';

function getBase64(img: RcFile, callback: { (imageUrl: any): void; (arg0: string | ArrayBuffer | null): any; }) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

function Person() {
    const [user, setUser] = useState({ nickname: '', avatar: '', pwd: '', account: '',ctime:0 })
    const [resetUrl, setResetUrl] = useState('')  //更新头像
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState('');    //头像
    const [isModalVisible, setIsModalVisible] = useState(false);  //修改头像的弹窗
    const [showEditNick, setShowEditNick] = useState(false);  //编辑图标
    const [visibleConf, setVisibleConf] = useState(false);    //退出登录确认

    //初始化
    useEffect(() => {
        getUserInfo().then((res) => {
            setUser(Object(res.data))
            if (res.data?.avatar)
                setResetUrl(res.data?.avatar)
        })
    }, [])

    //弹出对话框
    const showModal = () => {
        setIsModalVisible(true);
    };
    const handleOk = () => {
        setIsModalVisible(false);
        setResetUrl(imageUrl);
        //上传
        let userTemp = user;
        userTemp.nickname = user.nickname
        userTemp.avatar = imageUrl
        updateUserInfo(userTemp)
    };
    const handleCancel = () => {
        setIsModalVisible(false);
    };

    //图片上传前预览
    const handleChange = (info: UploadChangeParam<UploadFile<any>>) => {
        if (info.file.status === 'uploading') {
            setLoading(true)
            return;
        }
        if (info.file.status === 'done') {
            setLoading(false)
            if (info.file.originFileObj)
                getBase64(info.file.originFileObj, imageUrl =>
                    setImageUrl(String(imageUrl))
                );
        }
    };
    function beforeUpload(file: RcFile) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('仅支持 JPG/PNG 文件!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('图片必须小于 2MB!');
        }
        getBase64(file, imageUrl => {
            setImageUrl(imageUrl)
        })
        return false;
    }

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    return (
        <div className={style.warp}>
            <div className={style.header}>
                <div>
                    <div onClick={showModal} className={style.avaCover}>
                        <Avatar size={128} src={resetUrl} icon={<UserOutlined />} />
                    </div>
                    <Modal title="更新头像" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}
                        closable={false} className={style.avatar}>
                        <div className={style.upload}>
                            <Upload
                                name="avatar"
                                className="avatar-uploader"
                                listType="picture-card"
                                showUploadList={false}
                                action="/api/file/upload"
                                beforeUpload={beforeUpload}
                                onChange={(e) => handleChange(e)}
                            >
                                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                        </div>
                    </Modal>
                </div>
                {showEditNick ?
                    <div>
                        <Popconfirm
                            title={`是否要修改昵称为${user.nickname}?`}
                            visible={visibleConf}
                            onConfirm={() => {
                                setVisibleConf(false);
                                updateUserInfo(user);
                                setShowEditNick(false);
                            }}
                            onCancel={() => setVisibleConf(false)}
                            okText="修改"
                            cancelText="取消"
                        >
                            <input type="text"
                                maxLength={6}
                                autoFocus={true}  //自动获取焦点
                                value={user.nickname}
                                onChange={(e) => {
                                    const newUser = Object.assign({}, user, { nickname: e.target.value });
                                    setUser(newUser)
                                }}
                                onDoubleClick={() => { setShowEditNick(false) }}
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter') {
                                        setVisibleConf(true)
                                    }
                                }}
                            />
                        </Popconfirm>
                    </div>
                    : <div onDoubleClick={() => { setShowEditNick(true) }}>
                        <Text style={{ width: 120 ,display:'inline'}} ellipsis={true}>{user.nickname ? user.nickname : '用户' + user.account}</Text>
                        <EditOutlined onClick={() => { setShowEditNick(true) }} />
                    </div>
                }
            </div>
            <div className={style.container}>
                <div className={style.sider}>
                    <ul>
                        <li><NavLink to="/">首页</NavLink></li>
                        <li><NavLink to="/Person/Add">添加创作</NavLink></li>
                        <li>
                            <Popconfirm
                                placement="rightBottom"
                                title="确定要退出登录吗？"
                                onConfirm={() => { logout(); window.location.href = "/" }}
                                okText="确定"
                                cancelText="取消"
                            >
                                <a>退出登录</a>
                            </Popconfirm>
                        </li>
                    </ul>
                    <div><span style={{fontSize:14,color:'#aaa'}}>于<span style={{color:'rgb(138, 104, 72)'}}>{moment(user.ctime).format("YYYY-MM-DD")}</span>加入</span></div>
                </div>
                <div className={style.list}>
                    <MyArticle></MyArticle>
                </div>
            </div>
        </div>
    )
}
export default Person